package com.mairuide._frame.utils.sheethandler;

import com.mairuide._frame.utils.ReflectUtils;
import com.mairuide._frame.utils.RegUtil;
import com.mairuide._frame.utils.SpringUtil;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.exceltitle_dict.enum2.FieldTypeEnum;
import com.mairuide.exceltitle_dict.enum2.PackageNameEnum;
import com.mairuide.exceltitle_dict.pojo.ExceltitleDict;
import com.mairuide.exceltitle_dict.service.ExceltitleDictService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-05-14 9:12
 * 处理03版的excel，因为sax不支持03的
 */
public class Excel03SheetHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private AtomicInteger count = new AtomicInteger(0);
    private static List<ExceltitleDict> exceltitleDictList = null;
    private Map<String,Object> resultMap = new HashMap<String,Object>();  //结果MAP
    private Map<String,Object> paraMap = new HashMap<String,Object>();  //参数MAP
    private Map<Integer,ExceltitleDict> exceltitleDictMap =new HashMap<Integer,ExceltitleDict>();
    private  List<DealFlow> data = new ArrayList<DealFlow>();

    public  void deal(Workbook wb){
        Iterator<Sheet> sheetIterator = wb.sheetIterator();
        while(sheetIterator.hasNext()){
            Sheet sheet = sheetIterator.next();
            int numberOfRows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < numberOfRows; i++) {
                check();
                Row row = sheet.getRow(i);
                if (row==null) continue;
                int physicalNumberOfCells = row.getPhysicalNumberOfCells();
                DealFlow dealFlow = new DealFlow();
                for (int j = 0; j < physicalNumberOfCells; j++) {
                    Cell cell = row.getCell(j);
                    if (cell==null) continue;
                    //cell.setCellType(Cell.CELL_TYPE_STRING);
                    DataFormatter formatter = new DataFormatter();
                    String val = formatter.formatCellValue(cell);
                    String cellValue = val;
                    Object object = null;
                    if (cellValue!=null){
                        cellValue= RegUtil.replaceBlank(cellValue);
                        object = cellValue;
                    }
                    if (StringUtils.isBlank(cellValue)) continue;
                    //System.out.println(cellValue);
                    if (i==0){
                        getExceltitleDictList();
                        for (int k = 0; k < exceltitleDictList.size(); k++) {
                            String titleValues = exceltitleDictList.get(k).getTitleValues();
                            if (cellValue.equals(titleValues)){
                                exceltitleDictMap.put(j,exceltitleDictList.get(k));
                            }
                        }
                    }else{
                        //如果标题头小于3个就跳出，因为插入的数据也没意义
                        if (exceltitleDictMap.size()<3) {
                            break;
                        }
                        ExceltitleDict exceltitleDict = exceltitleDictMap.get(j);
                        if (exceltitleDict!=null){
                            String classField = exceltitleDict.getClassField();
                            try {
                                Class aClass = FieldTypeEnum.getFieldTypeEnumByVal(exceltitleDict.getFieldType());
                                if (aClass.equals(Timestamp.class) ){
                                    Date d= DateUtils.getDate(cellValue);
                                    if (d==null) continue;
                                    object = new Timestamp( d.getTime());
                                }else if (aClass.equals(BigDecimal.class) ){
                                    object=new BigDecimal(cellValue);
                                }else if (aClass.equals(Integer.class) ){
                                    if("sign".equals(classField)){
                                        if ("出取1D借".contains(cellValue)){
                                            object=1;
                                        }else if ("进存贷C0".contains(cellValue)){
                                            object=0;
                                        }else {
                                            object=0;
                                        }
                                    }else{
                                        object=Integer.valueOf(cellValue);
                                    }
                                }
                                ReflectUtils.setValue(dealFlow, DealFlow.class,classField,aClass,object);
                            } catch (NumberFormatException e) {
                                logger.info("导入报错》》》值为："+object+",字段为："+classField+",第"+i+"行");
                                e.printStackTrace();
                            }
                        }
                    }
                }
                if (i!=0&&exceltitleDictMap.size()>3){
                    if(StringUtils.isBlank(dealFlow.getAccountRivalCard())&&StringUtils.isNotBlank(dealFlow.getAccountRivalNumber())){
                        dealFlow.setAccountRivalCard(dealFlow.getAccountRivalNumber());
                    }
                    if(StringUtils.isBlank(dealFlow.getAccountBodyCard())&&StringUtils.isNotBlank(dealFlow.getAccountBodyNumber())){
                        dealFlow.setAccountBodyCard(dealFlow.getAccountBodyNumber());
                    }
                    if (dealFlow.getSign()==null){
                        dealFlow.setSign(1);
                    }
                    data.add(dealFlow);
                    int successNum = count.incrementAndGet();
                    resultMap.put("successNum",successNum);
                }
            }
        }
    }

    public void getExceltitleDictList(){
        ExceltitleDictService exceltitleDictService = SpringUtil.getBean(ExceltitleDictService.class);
        this.exceltitleDictList = exceltitleDictService.getListByPackageName(PackageNameEnum.DEALFLOW.getPackageName());
    }

    public void check(){
        if (data.size()>=10000){
            doSomething();
            data = new ArrayList<DealFlow>();
        }
    }


    public void doSomething(){
        for (int i = 0; i < data.size(); i++) {
            DealFlow dealFlow = data.get(i);
            dealFlow.setUuid((String)paraMap.get("uuid"));
            dealFlow.setCasemanageId((String)paraMap.get("uid"));
            dealFlow.setCreateId((Integer) paraMap.get("platManagerId"));
            dealFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
            dealFlow.setIsDelete(0);
            if(StringUtils.isEmpty(dealFlow.getAccountBodyCard()) && StringUtils.isEmpty(dealFlow.getAccountBodyNumber())) {
            	data.remove(dealFlow);
            }
        }
        DealFlowService dealFlowService = SpringUtil.getBean(DealFlowService.class);
        dealFlowService.batchSave(data);
    }

    public Map<String, Object> getResultMap() {
        return resultMap;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

    public Map<String, Object> getParaMap() {
        return paraMap;
    }

    public void setParaMap(Map<String, Object> paraMap) {
        this.paraMap = paraMap;
    }

    public List<DealFlow> getData() {
        return data;
    }

    public void setData(List<DealFlow> data) {
        this.data = data;
    }
}
